package com.houger.ddd.advice;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.houger.ddd.common.utils.BusinessException;
import com.houger.ddd.common.utils.R;
import com.houger.ddd.common.utils.StatusCode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

/**
 * 统一业务异常
 * Created by jiayong.yang on 2015/12/29.
 */
@Slf4j
@RestControllerAdvice
public class AppControllerAdvice {

//    @ExceptionHandler(Exception.class)
//    public R<String> handlerDefaultException(HttpServletRequest request, HttpServletResponse response, Exception e){
//        log.error("uri:{} error:{}",request.getRequestURI(),ExceptionUtils.getMessage(e));
//        response.setStatus(StatusCode.ERROR.getCode());
//        return R.error(StatusCode.ERROR.getCode(),ExceptionUtils.getMessage(e));
//    }

    @ExceptionHandler(IllegalAccessException.class)
    public R<String> handlerAssertException(HttpServletRequest request,IllegalAccessException e){
        log.error("uri:{} error:{}",request.getRequestURI(),ExceptionUtils.getMessage(e));
        return R.error(StatusCode.INVALID_PARAM.getCode(),ExceptionUtils.getMessage(e));
    }

    @ExceptionHandler(BusinessException.class)
    public R<String> handlerGatewayException(HttpServletRequest request,BusinessException e){
        log.error("uri:{} error:{}",request.getRequestURI(),ExceptionUtils.getMessage(e));
        return R.error(e.getStatusCode().getCode(),e.getStatusCode().getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<String> handleValidateException(HttpServletRequest request,MethodArgumentNotValidException e){
        log.error("uri:{} error:{}",request.getRequestURI(),ExceptionUtils.getMessage(e));
        return R.error(StatusCode.INVALID_PARAM.getCode(),ExceptionUtils.getMessage(e));
    }

//    @ExceptionHandler(Throwable.class)
//    public R<String> processUnexpectedError(Throwable ex) {
//    	long traceCode = System.currentTimeMillis();
//        log.error("UNEXPECTED_ERROR-"+traceCode,ex);
//
//        if(ex instanceof FlowException) {
//            return R.error(StatusCode.RESP_CODE_FLOW_LIMITING_EXCEPTION.getCode(),ExceptionUtils.getMessage(ex));
//        }
//		return R.error(StatusCode.DEFAULT_FAIL.getCode(),"未知异常，错误代码:"+traceCode);
//    }
}
